<!--  -->
<template>
  <div
    ref="container"
    class="w-100vw h-100vh sm:grid sm:grid-cols-1 sm:grid-rows-[1fr_5fr_100px]"
  >
    <!-- head -->
    <div class="hidden sm:flex items-center justify-around">
      <img
        class="w-400px lg:w-730px"
        :style="layer0"
        :src="themeStore.logo"
      >
      <div class="text-20px xl:text-30px whitespace-nowrap flex justify-end">
        客服热线：<span class="color-[--el-color-primary]">{{ themeStore.telephone }}</span>
      </div>
    </div>
    <div class="w-100vw overflow-hidden relative flex items-center justify-center">
      <div class="w-full h-full bgimg absolute z-{-1} dark:brightness-60" />
      <!-- login -->
      <div
        class="login w-100% h-100vh backdrop-blur-lg bg-white/30 dark:bg-black/30 flex flex-col items-center justify-around p-30px box-border sm:w-480px sm:h-520px xl:ml-46% sm:mr-0 sm:shadow-[0px_0px_0px_10px_rgba(185,203,247,0.12)] transition-all duration-300"
      >
        <div class="flex justify-center items-center h-160px w-100%">
          <div class="w-20% h-3px bg-#dcdfe6" />
          <div class="p-x-20px text-xl">
            欢迎登录
          </div>
          <div class="w-20% h-3px bg-#dcdfe6" />
        </div>
        <el-form
          ref="form"
          class="w-260px"
          :rules="rules"
          :model="userForm"
          @submit.prevent="handleSubmit"
        >
          <el-form-item prop="username">
            <el-input
              v-model="userForm.username"
              placeholder="请输入用户名"
              :prefix-icon="IconUser"
            />
          </el-form-item>
          <el-form-item prop="password">
            <el-input
              v-model="userForm.password"
              placeholder="请输入密码"
              :prefix-icon="IconLock"
              type="password"
              show-password
            />
          </el-form-item>
          <el-form-item prop="code">
            <el-input
              v-model="userForm.code"
              class="input-append"
            >
              <template #append>
                <el-button
                  :disabled="disabled"
                  @click="getCode"
                >
                  {{ str }}
                </el-button>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item>
            <el-checkbox
              v-model="userForm.cookie"
              label="记住账号密码"
            />
          </el-form-item>
          <!-- <el-form-item>
            <el-checkbox
              v-model="consent"
              label="勾选即代表您同意"
            />
            <el-link
              type="primary"
              :underline="false"
            >
              《平台注册协议》
            </el-link>
            <el-link
              type="primary"
              :underline="false"
            >
              《平台交易协议》
            </el-link>
          </el-form-item> -->

          <el-form-item>
            <el-button
              style="width: 100%;"
              type="primary"
              :loading="loading"
              native-type="submit"
            >
              登录
            </el-button>
          </el-form-item>
        </el-form>
        <img
          class="w-100px"
          :src="themeStore.WeChat"
          alt=""
        >
      </div>
    </div>
    <div class="hidden sm:flex flex-col items-center justify-center">
      <div>
        版权所有：{{ themeStore.companyName }}
      </div>
      <div>
        <a
          target="_blank"
          href="https://beian.miit.gov.cn/"
          style="text-decoration:none;"
        >{{ themeStore.IPC }}</a>
        {{ themeStore.Copyright }}
      </div>
    </div>
  </div>
</template>
<script setup>
import { login, loginCode } from '@/api/common'
import { User as IconUser, Lock as IconLock } from '@element-plus/icons-vue'
import useUserStore from '@/store/user'
import useThemeStore from '@/store/theme'
import { useParallax } from '@vueuse/core'

import NodeCode from '@/composables/CodeNode'

const themeStore = useThemeStore()

const bg = `url(${themeStore.loginBg}) no-repeat center`

const userStore = useUserStore()

const userForm = reactive({ ...userStore.form })

const rules = reactive({
  username: [{ required: true, message: '请输入账号', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
  code: [{ required: true, message: '请输入验证码', trigger: 'blur' }]
})
const loading = ref(false)
const form = ref(null)

const router = useRouter()
const route = useRoute()

// 短信验证码
let nodeCode = null

// 监听倒计时数据
const str = ref('')
const disabled = ref(false)
const init = () => {
  /**
   * 倒计时
   * @param {String} queKey - 唯一标识, 如果存在, 在H5刷新或各端返回再进入时继续倒计时
   * @param {Number} seconds - 倒计时时长 默认60s
   * @return {Object}
   */
  nodeCode = new NodeCode()

  nodeCode.change((data) => {
    str.value = data.msg
    disabled.value = data.disabled
  })
}

onMounted(init)

onUnmounted(() => {
  // 销毁定时装置
  nodeCode.off()
})

// 发送验证码
const getCode = async () => {
  await form.value?.validateField('username')
  // 开启倒计时
  nodeCode.start()
  const data = await loginCode(userForm)
  userForm.dxToken = data
}

// const consent = ref(false)
const handleSubmit = async () => {
  // if (!consent.value) {
  //   ElMessage({
  //     message: '请先勾选同意 《平台注册协议》《平台交易协议》',
  //     type: 'warning'
  //   })
  //   return
  // }
  // 表单验证
  await form.value?.validate()

  // 验证通过，展示 loading
  loading.value = true

  // 请求登录
  const token = await login(userForm).finally(() => {
    loading.value = false
  })

  // 储存Token信息
  userStore.setToken(token)
  // 储存账号密码
  if (userForm.cookie) {
    userStore.setForm(userForm)
  } else {
    userStore.setForm()
  }

  // 跳转页面
  let redirect = route.query.redirect || '/'

  // 容错处理  redirect有可能是  LocationQueryValue[]
  if (typeof redirect !== 'string') {
    redirect = '/'
  }
  router.replace(redirect)
}

const container = ref(null)
const { tilt, roll } = useParallax(container)

const layer0 = computed(() => ({
  transition: '.3s ease-out all',
  transform: `translateX(${tilt.value * 10}px) translateY(${roll.value * -10
    }px)`
}))

</script>

<style scoped lang='scss'>
.input-append{
  :deep(.el-input-group__append){
    background-color: var(--el-input-bg-color,var(--el-fill-color-blank));
  }
}
.bgimg {
  background: v-bind('bg');
}

</style>
